// XHook - v1.4.9 - https://github.com/jpillora/xhook
// Jaime Pillora <dev@jpillora.com> - MIT Copyright 2018
(function (undefined) {
  var AFTER, BEFORE, COMMON_EVENTS, EventEmitter, FETCH, FIRE, FormData, NativeFetch, NativeFormData, NativeXMLHttp, OFF, ON, READY_STATE, UPLOAD_EVENTS, WINDOW, XHookFetchRequest, XHookFormData, XHookHttpRequest, XMLHTTP, convertHeaders, depricatedProp, document, fakeEvent, mergeObjects, msie, nullify, proxyEvents, slice, useragent, xhook, _base,
    __indexOf = [].indexOf || function (item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  WINDOW = null;

  if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
    WINDOW = self;
  } else if (typeof global !== 'undefined') {
    WINDOW = global;
  } else {
    WINDOW = window;
  }

  document = WINDOW.document;

  BEFORE = 'before';

  AFTER = 'after';

  READY_STATE = 'readyState';

  ON = 'addEventListener';

  OFF = 'removeEventListener';

  FIRE = 'dispatchEvent';

  XMLHTTP = 'XMLHttpRequest';

  FETCH = 'fetch';

  FormData = 'FormData';

  UPLOAD_EVENTS = ['load', 'loadend', 'loadstart'];

  COMMON_EVENTS = ['progress', 'abort', 'error', 'timeout'];

  useragent = typeof navigator !== 'undefined' && navigator['useragent'] ? navigator.userAgent : '';

  msie = parseInt((/msie (\d+)/.exec(useragent.toLowerCase()) || [])[1]);

  if (isNaN(msie)) {
    msie = parseInt((/trident\/.*; rv:(\d+)/.exec(useragent.toLowerCase()) || [])[1]);
  }

  (_base = Array.prototype).indexOf || (_base.indexOf = function (item) {
    var i, x, _i, _len;
    for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) {
      x = this[i];
      if (x === item) {
        return i;
      }
    }
    return -1;
  });

  slice = function (o, n) {
    return Array.prototype.slice.call(o, n);
  };

  depricatedProp = function (p) {
    return p === "returnValue" || p === "totalSize" || p === "position";
  };

  mergeObjects = function (src, dst) {
    var k, v;
    for (k in src) {
      v = src[k];
      if (depricatedProp(k)) {
        continue;
      }
      try {
        dst[k] = src[k];
      } catch (_error) { }
    }
    return dst;
  };

  nullify = function (res) {
    if (res === void 0) {
      return null;
    }
    return res;
  };

  proxyEvents = function (events, src, dst) {
    var event, p, _i, _len;
    p = function (event) {
      return function (e) {
        var clone, k, val;
        clone = {};
        for (k in e) {
          if (depricatedProp(k)) {
            continue;
          }
          val = e[k];
          clone[k] = val === src ? dst : val;
        }
        return dst[FIRE](event, clone);
      };
    };
    for (_i = 0, _len = events.length; _i < _len; _i++) {
      event = events[_i];
      if (dst._has(event)) {
        src["on" + event] = p(event);
      }
    }
  };

  fakeEvent = function (type) {
    var msieEventObject;
    if (document && (document.createEventObject != null)) {
      msieEventObject = document.createEventObject();
      msieEventObject.type = type;
      return msieEventObject;
    } else {
      try {
        return new Event(type);
      } catch (_error) {
        return {
          type: type
        };
      }
    }
  };

  EventEmitter = function (nodeStyle) {
    var emitter, events, listeners;
    events = {};
    listeners = function (event) {
      return events[event] || [];
    };
    emitter = {};
    emitter.getEvents=()=>{
      return events;
    }
    emitter.removeHookByEffectUrl=(url)=>{

      'before after'.split(' ').forEach((type)=>{
        events[type].forEach((fn,index)=>{
          if(url==fn.effectUrl){
            events[type].splice(index,1)
          }
        
          // HACKER.doNothing('fn and index--:',fn,index)
        })
      })

      
    }
    emitter.clearHooks = () => {
      // HACKER.doNothing('events--------:',events.before[0].effectUrl)
      for (let i in events) {
        HACKER.doNothing('will delete events--:',i);//

        events[i]=events[i].filter((o)=>o.effectUrl=='*')
        // [].concat(events[i]).forEach((evt)=>{
        //   // HACKER.doNothing('evt----:',evt,evt.effectUrl)
        // })

        
        // if (events.hasOwnProperty(i)) {
        //   delete events[i]
        // }

      }
    }
    emitter[ON] = function (event, callback, i) {
      events[event] = listeners(event);
      if (events[event].indexOf(callback) >= 0) {
        return;
      }
      i = i === undefined ? events[event].length : i;
      events[event].splice(i, 0, callback);
    };
    emitter[OFF] = function (event, callback) {
      var i;
      if (event === undefined) {
        events = {};
        return;
      }
      if (callback === undefined) {
        events[event] = [];
      }
      i = listeners(event).indexOf(callback);
      if (i === -1) {
        return;
      }
      listeners(event).splice(i, 1);
    };
    emitter[FIRE] = function () {
      var args, event, i, legacylistener, listener, _i, _len, _ref;
      args = slice(arguments);
      event = args.shift();
      if (!nodeStyle) {
        args[0] = mergeObjects(args[0], fakeEvent(event));
      }
      legacylistener = emitter["on" + event];
      if (legacylistener) {
        legacylistener.apply(emitter, args);
      }
      _ref = listeners(event).concat(listeners("*"));
      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
        listener = _ref[i];
        listener.apply(emitter, args);
      }
    };
    emitter._has = function (event) {
      return !!(events[event] || emitter["on" + event]);
    };
    if (nodeStyle) {
      emitter.listeners = function (event) {
        return slice(listeners(event));
      };
      emitter.on = emitter[ON];
      emitter.off = emitter[OFF];
      emitter.fire = emitter[FIRE];
      emitter.once = function (e, fn) {
        var fire;
        fire = function () {
          emitter.off(e, fire);
          return fn.apply(null, arguments);
        };
        return emitter.on(e, fire);
      };
      emitter.destroy = function () {
        return events = {};
      };
    }
    return emitter;
  };

  xhook = EventEmitter(true);

  xhook.EventEmitter = EventEmitter;

  xhook[BEFORE] = function (handler, i) {
    if (handler.length < 1 || handler.length > 2) {
      throw "invalid hook";
    }
    return xhook[ON](BEFORE, handler, i);
  };

  xhook[AFTER] = function (handler, i) {
    if (handler.length < 2 || handler.length > 3) {
      throw "invalid hook";
    }
    return xhook[ON](AFTER, handler, i);
  };

  xhook.enable = function () {
    WINDOW[XMLHTTP] = XHookHttpRequest;
    if (typeof XHookFetchRequest === "function") {
      WINDOW[FETCH] = XHookFetchRequest;
    }
    if (NativeFormData) {
      //  WINDOW[FormData] = XHookFormData;
    }
  };

  xhook.disable = function () {
    WINDOW[XMLHTTP] = xhook[XMLHTTP];
    WINDOW[FETCH] = xhook[FETCH];
    if (NativeFormData) {
      WINDOW[FormData] = NativeFormData;
    }
  };

  convertHeaders = xhook.headers = function (h, dest) {
    var header, headers, k, name, v, value, _i, _len, _ref;
    if (dest == null) {
      dest = {};
    }
    switch (typeof h) {
      case "object":
        headers = [];
        for (k in h) {
          v = h[k];
          name = k.toLowerCase();
          headers.push("" + name + ":\t" + v);
        }
        return headers.join('\n') + '\n';
      case "string":
        headers = h.split('\n');
        for (_i = 0, _len = headers.length; _i < _len; _i++) {
          header = headers[_i];
          if (/([^:]+):\s*(.+)/.test(header)) {
            name = (_ref = RegExp.$1) != null ? _ref.toLowerCase() : void 0;
            value = RegExp.$2;
            if (dest[name] == null) {
              dest[name] = value;
            }
          }
        }
        return dest;
    }
  };

  NativeFormData = WINDOW[FormData];

  XHookFormData = function (form) {
    var entries;
    this.fd = form ? new NativeFormData(form) : new NativeFormData();
    this.form = form;
    entries = [];
    Object.defineProperty(this, 'entries', {
      get: function () {
        var fentries;
        fentries = !form ? [] : slice(form.querySelectorAll("input,select")).filter(function (e) {
          var _ref;
          return ((_ref = e.type) !== 'checkbox' && _ref !== 'radio') || e.checked;
        }).map(function (e) {
          return [e.name, e.type === "file" ? e.files : e.value];
        });
        return fentries.concat(entries);
      }
    });
    this.append = (function (_this) {
      return function () {
        var args;
        args = slice(arguments);
        entries.push(args);
        return _this.fd.append.apply(_this.fd, args);
      };
    })(this);
  };

  if (NativeFormData) {
    xhook[FormData] = NativeFormData;
    // WINDOW[FormData] = XHookFormData;
  }

  NativeXMLHttp = WINDOW[XMLHTTP];

  xhook[XMLHTTP] = NativeXMLHttp;

  XHookHttpRequest = WINDOW[XMLHTTP] = function () {
    var ABORTED, currentState, emitFinal, emitReadyState, event, facade, hasError, hasErrorHandler, readBody, readHead, request, response, setReadyState, status, transiting, writeBody, writeHead, xhr, _i, _len, _ref;
    ABORTED = -1;
    xhr = new xhook[XMLHTTP]();
    request = {};
    status = null;
    hasError = void 0;
    transiting = void 0;
    response = void 0;
    readHead = function () {
      var key, name, val, _ref;
      response.status = status || xhr.status;
      if (!(status === ABORTED && msie < 10)) {
        response.statusText = xhr.statusText;
      }
      if (status !== ABORTED) {
        _ref = convertHeaders(xhr.getAllResponseHeaders());
        for (key in _ref) {
          val = _ref[key];
          if (!response.headers[key]) {
            name = key.toLowerCase();
            response.headers[name] = val;
          }
        }
      }
    };
    readBody = function () {
      if (!xhr.responseType || xhr.responseType === "text") {
        response.text = xhr.responseText;
        response.data = xhr.responseText;
        try {
          response.xml = xhr.responseXML;
        } catch (_error) {

        }
      } else if (xhr.responseType === "document") {
        response.xml = xhr.responseXML;
        response.data = xhr.responseXML;
      } else {
        response.data = xhr.response;
      }
      if ("responseURL" in xhr) {
        response.finalUrl = xhr.responseURL;
      }
    };
    writeHead = function () {
      facade.status = response.status;
      facade.statusText = response.statusText;
    };
    writeBody = function () {
      if ('text' in response) {
        facade.responseText = response.text;
      }
      if ('xml' in response) {
        facade.responseXML = response.xml;
      }
      if ('data' in response) {
        facade.response = response.data;
      }
      if ('finalUrl' in response) {
        facade.responseURL = response.finalUrl;
      }
    };
    emitReadyState = function (n) {
      while (n > currentState && currentState < 4) {
        facade[READY_STATE] = ++currentState;
        if (currentState === 1) {
          facade[FIRE]("loadstart", {});
        }
        if (currentState === 2) {
          writeHead();
        }
        if (currentState === 4) {
          writeHead();
          writeBody();
        }
        facade[FIRE]("readystatechange", {});
        if (currentState === 4) {
          if (request.async === false) {
            emitFinal();
          } else {
            setTimeout(emitFinal, 0);
          }
        }
      }
    };
    emitFinal = function () {
      if (!hasError) {
        facade[FIRE]("load", {});
      }
      facade[FIRE]("loadend", {});
      if (hasError) {
        facade[READY_STATE] = 0;
      }
    };
    currentState = 0;
    setReadyState = function (n) {
      var hooks, process;
      if (n !== 4) {
        emitReadyState(n);
        return;
      }
      hooks = xhook.listeners(AFTER);
      process = function () {
        var hook;
        if (!hooks.length) {
          return emitReadyState(4);
        }
        hook = hooks.shift();
        if (hook.length === 2) {
          hook(request, response);
          return process();
        } else if (hook.length === 3 && request.async) {
          return hook(request, response, process);
        } else {
          return process();
        }
      };
      process();
    };
    facade = request.xhr = EventEmitter();
    xhr.onreadystatechange = function (event) {
      try {
        if (xhr[READY_STATE] === 2) {
          readHead();
        }
      } catch (_error) { }
      if (xhr[READY_STATE] === 4) {
        transiting = false;
        readHead();
        readBody();
      }
      setReadyState(xhr[READY_STATE]);
    };
    hasErrorHandler = function () {
      hasError = true;
    };
    facade[ON]('error', hasErrorHandler);
    facade[ON]('timeout', hasErrorHandler);
    facade[ON]('abort', hasErrorHandler);
    facade[ON]('progress', function () {
      if (currentState < 3) {
        setReadyState(3);
      } else {
        facade[FIRE]("readystatechange", {});
      }
    });
    if ('withCredentials' in xhr || xhook.addWithCredentials) {
      facade.withCredentials = false;
    }
    facade.status = 0;
    _ref = COMMON_EVENTS.concat(UPLOAD_EVENTS);
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      event = _ref[_i];
      facade["on" + event] = null;
    }
    facade.open = function (method, url, async, user, pass) {
      currentState = 0;
      hasError = false;
      transiting = false;
      request.headers = {};
      request.headerNames = {};
      request.status = 0;
      response = {};
      response.headers = {};
      request.method = method;
      request.url = url;
      request.async = async !== false;
      request.user = user;
      request.pass = pass;
      setReadyState(1);
    };
    facade.send = function (body) {
      var hooks, k, modk, process, send, _j, _len1, _ref1;
      _ref1 = ['type', 'timeout', 'withCredentials'];
      for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
        k = _ref1[_j];
        modk = k === "type" ? "responseType" : k;
        if (modk in facade) {
          request[k] = facade[modk];
        }
      }
      request.body = body;
      send = function () {
        var header, value, _k, _len2, _ref2, _ref3;
        proxyEvents(COMMON_EVENTS, xhr, facade);
        if (facade.upload) {
          proxyEvents(COMMON_EVENTS.concat(UPLOAD_EVENTS), xhr.upload, facade.upload);
        }
        transiting = true;
        xhr.open(request.method, request.url, request.async, request.user, request.pass);
        _ref2 = ['type', 'timeout', 'withCredentials'];
        for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
          k = _ref2[_k];
          modk = k === "type" ? "responseType" : k;
          if (k in request) {
            xhr[modk] = request[k];
          }
        }
        _ref3 = request.headers;
        for (header in _ref3) {
          value = _ref3[header];
          if (header) {
            xhr.setRequestHeader(header, value);
          }
        }
        if (request.body instanceof XHookFormData) {
          request.body = request.body.fd;
        }
        xhr.send(request.body);
      };
      hooks = xhook.listeners(BEFORE);
      process = function () {
        var done, hook;
        if (!hooks.length) {
          return send();
        }
        done = function (userResponse) {
          if (typeof userResponse === 'object' && (typeof userResponse.status === 'number' || typeof response.status === 'number')) {
            mergeObjects(userResponse, response);
            if (__indexOf.call(userResponse, 'data') < 0) {
              userResponse.data = userResponse.response || userResponse.text;
            }
            setReadyState(4);
            return;
          }
          process();
        };
        done.head = function (userResponse) {
          mergeObjects(userResponse, response);
          return setReadyState(2);
        };
        done.progress = function (userResponse) {
          mergeObjects(userResponse, response);
          return setReadyState(3);
        };
        hook = hooks.shift();
        if (hook.length === 1) {
          return done(hook(request));
        } else if (hook.length === 2 && request.async) {
          return hook(request, done);
        } else {
          return done();
        }
      };
      process();
    };
    facade.abort = function () {
      status = ABORTED;
      if (transiting) {
        xhr.abort();
      } else {
        facade[FIRE]('abort', {});
      }
    };
    facade.setRequestHeader = function (header, value) {
      var lName, name;
      lName = header != null ? header.toLowerCase() : void 0;
      name = request.headerNames[lName] = request.headerNames[lName] || header;
      if (request.headers[name]) {
        value = request.headers[name] + ', ' + value;
      }
      request.headers[name] = value;
    };
    facade.getResponseHeader = function (header) {
      var name;
      name = header != null ? header.toLowerCase() : void 0;
      return nullify(response.headers[name]);
    };
    facade.getAllResponseHeaders = function () {
      return nullify(convertHeaders(response.headers));
    };
    if (xhr.overrideMimeType) {
      facade.overrideMimeType = function () {
        return xhr.overrideMimeType.apply(xhr, arguments);
      };
    }
    if (xhr.upload) {
      facade.upload = request.upload = EventEmitter();
    }
    facade.UNSENT = 0;
    facade.OPENED = 1;
    facade.HEADERS_RECEIVED = 2;
    facade.LOADING = 3;
    facade.DONE = 4;
    facade.response = '';
    facade.responseText = '';
    facade.responseXML = null;
    facade.readyState = 0;
    facade.statusText = '';
    return facade;
  };

  if (typeof WINDOW[FETCH] === "function") {
    NativeFetch = WINDOW[FETCH];
    xhook[FETCH] = NativeFetch;
    XHookFetchRequest = WINDOW[FETCH] = function (url, options) {
      var afterHooks, beforeHooks, request;
      if (options == null) {
        options = {
          headers: {}
        };
      }
      options.url = url;
      request = null;
      beforeHooks = xhook.listeners(BEFORE);
      afterHooks = xhook.listeners(AFTER);
      return new Promise(function (resolve, reject) {
        var done, getRequest, processAfter, processBefore, send;
        getRequest = function () {
          if (options.body instanceof XHookFormData) {
            options.body = options.body.fd;
          }
          if (options.headers) {
            options.headers = new Headers(options.headers);
          }
          if (!request) {
            request = new Request(options.url, options);
          }
          return mergeObjects(options, request);
        };
        processAfter = function (response) {
          var hook;
          if (!afterHooks.length) {
            return resolve(response);
          }
          hook = afterHooks.shift();
          if (hook.length === 2) {
            hook(getRequest(), response);
            return processAfter(response);
          } else if (hook.length === 3) {
            return hook(getRequest(), response, processAfter);
          } else {
            return processAfter(response);
          }
        };
        done = function (userResponse) {
          var response;
          if (userResponse !== void 0) {
            response = new Response(userResponse.body || userResponse.text, userResponse);
            resolve(response);
            processAfter(response);
            return;
          }
          processBefore();
        };
        processBefore = function () {
          var hook;
          if (!beforeHooks.length) {
            send();
            return;
          }
          hook = beforeHooks.shift();
          if (hook.length === 1) {
            return done(hook(options));
          } else if (hook.length === 2) {
            return hook(getRequest(), done);
          }
        };
        send = function () {
          return NativeFetch(getRequest()).then(function (response) {
            return processAfter(response);
          })["catch"](function (err) {
            processAfter(err);
            return reject(err);
          });
        };
        processBefore();
      });
    };
  }

  XHookHttpRequest.UNSENT = 0;

  XHookHttpRequest.OPENED = 1;

  XHookHttpRequest.HEADERS_RECEIVED = 2;

  XHookHttpRequest.LOADING = 3;

  XHookHttpRequest.DONE = 4;

  if (typeof define === "function" && define.amd) {
    define("xhook", [], function () {
      return xhook;
    });
  } else if (typeof module === "object" && module.exports) {
    module.exports = {
      xhook: xhook
    };
  } else if (WINDOW) {
    WINDOW.xhook = xhook;
  }

}.call(this));
